import { login, getUserInfo, getMyPermissions } from '@/api/user.js'

const getDefaultState = () => {
  return {
    token: localStorage.getItem('token'),
    userInfo: {}, // 当前用户的信息
    mypermissions: {} // 当前用户的权限
  }
}

const state = getDefaultState()

const mutations = {
  // 设置token
  setToken(state, token) {
    state.token = token
    localStorage.setItem('token', token)
  },
  // 设置用户详情
  getUserInfo(state, data) {
    state.userInfo = data
  },
  // 移除token
  removeToken(state) {
    state.token = ''
    localStorage.removeItem('token')
  },
  // 移除用户信息
  removeuserInfo(state) {
    state.userInfo = {}
  },
  // 设置用户权限
  setMyPermission(state, permission) {
    state.mypermissions = permission
    // console.log(state.mypermissions)
  }
}

const actions = {
  // 获取登录后返回的数据
  async login(store, data) {
    const res = await login(data)
    // console.log(res)
    store.state.token = res.data.jwt
    store.commit('setToken', res.data.jwt)
  },
  // 获取用户详情
  async getUserInfoDetail(store) {
    const res = await getUserInfo()
    // console.log(res)
    store.commit('getUserInfo', res.data)
    // 调用获取员工函数
    store.dispatch('getMyPermission')
  },
  // 退出登录
  async logOut(store) {
    store.commit('removeToken')
    store.commit('removeuserInfo')
  },
  // 获取当前用户的权限
  async getMyPermission(store) {
    const res = await getMyPermissions()
    // console.log(res)
    store.commit('setMyPermission', res.data.menus)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

